import { prisma } from "@/lib/prisma"
import { getServerSession } from "next-auth"
import { NextResponse } from "next/server"
import { authOptions } from "@/lib/auth"

export async function GET(
  req: Request,
  context: { params: { id: string } }
) {
  const { id } = await Promise.resolve(context.params)
  
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.isAdmin) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const events = await prisma.event.findMany({
      where: { libraryId: id },
      orderBy: { date: 'asc' }
    })

    return NextResponse.json(events)

  } catch (error) {
    return NextResponse.json(
      { error: "加载事件列表失败" },
      { status: 500 }
    )
  }
}

export async function POST(
  req: Request,
  context: { params: { id: string } }
) {
  const { id } = await Promise.resolve(context.params)
  
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.isAdmin) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const { title, description, date } = await req.json()

    const event = await prisma.event.create({
      data: {
        title,
        description,
        date: new Date(date),
        libraryId: id
      }
    })

    return NextResponse.json(event)

  } catch (error) {
    return NextResponse.json(
      { error: "创建事件失败" },
      { status: 500 }
    )
  }
} 